# -*- coding: utf-8 -*-
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        # ... [保持原有的UI设置代码不变，直到setupUi结束] ...
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # 新增初始化代码
        self.file_path_mapping = {}  # 存储文件名到完整路径的映射
        self.setup_connections()

    def setup_connections(self):
        """连接所有按钮的信号槽"""
        self.PicBtn.clicked.connect(self.open_image_file)
        self.FilesBtn.clicked.connect(self.open_image_folder)
        self.VideoBtn.clicked.connect(self.open_video_file)
        self.CapBtn.clicked.connect(self.open_camera)
        self.tableWidget.itemDoubleClicked.connect(self.on_table_double_click)

    # ========== 以下是新增的业务逻辑方法 ==========

    def open_image_file(self):
        """打开单个图片文件"""
        file_path, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, "选择图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp)")

        if file_path:
            self.process_single_file(file_path)

    def open_image_folder(self):
        """打开图片文件夹"""
        folder_path = QtWidgets.QFileDialog.getExistingDirectory(None, "选择文件夹")

        if folder_path:
            # 遍历文件夹中的图片文件
            for file in os.listdir(folder_path):
                if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                    full_path = os.path.join(folder_path, file)
                    self.process_single_file(full_path)

    def process_single_file(self, file_path):
        """处理单个文件并添加到表格"""
        file_name = os.path.basename(file_path)  # 提取纯文件名

        # 存储映射关系
        self.file_path_mapping[file_name] = file_path

        # 添加到表格
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)

        # 设置表格内容
        self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(str(row + 1)))  # 序号
        self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(file_name))  # 文件名
        self.tableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem("待检测"))  # 结果
        self.tableWidget.setItem(row, 3, QtWidgets.QTableWidgetItem(""))  # 置信度

        # 设置单元格对齐方式
        for col in [0, 2, 3]:
            item = self.tableWidget.item(row, col)
            item.setTextAlignment(QtCore.Qt.AlignCenter)

    def on_table_double_click(self, item):
        """双击表格项打开原始文件"""
        if item.column() == 1:  # 文件名列
            file_name = item.text()
            full_path = self.file_path_mapping.get(file_name)

            if full_path and os.path.exists(full_path):
                try:
                    if os.name == 'nt':  # Windows
                        os.startfile(full_path)
                    else:  # Mac/Linux
                        import subprocess
                        subprocess.call(('open', full_path))
                except Exception as e:
                    QtWidgets.QMessageBox.warning(None, "打开失败", f"无法打开文件:\n{str(e)}")

    # 以下是其他功能的占位方法，您可以根据需要实现
    def open_video_file(self):
        QtWidgets.QMessageBox.information(None, "提示", "视频导入功能待实现")

    def open_camera(self):
        QtWidgets.QMessageBox.information(None, "提示", "摄像头功能待实现")


# 主程序入口
if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())